<!-- Waterfall.vue -->
<template>
  <div class="waterfall-container">
    <!-- 瀑布流容器 -->
    <div class="waterfall-wrapper">
      <!-- 左侧列 -->
      <div class="waterfall-column">
        <div
          v-for="item in leftColumnItems"
          :key="item.id"
          class="waterfall-item overflow-hidden shadow-md transition-all duration-300 hover:shadow-xl"
          :data-id="item.id"
          @click="handleItemClick(item)"
        >
          <div class="relative overflow-hidden">
            <div
              v-if="!item.loaded"
              class="absolute inset-0 bg-gray-100 animate-pulse rounded-xl"
            />
            <img
              :src="item.cover"
              :alt="item.name"
              class="w-full h-auto object-contain transition-opacity duration-300 rounded-10"
              :class="{ 'opacity-0': !item.loaded }"
              @load="onImageLoad(item.id)"
            />
          </div>
          <div class="mt-8 text-999999 text-14">
            {{ item.name }}
          </div>
        </div>
      </div>

      <!-- 右侧列 -->
      <div class="waterfall-column">
        <div
          v-for="item in rightColumnItems"
          :key="item.id"
          class="waterfall-item overflow-hidden shadow-md transition-all duration-300 hover:shadow-xl"
          :data-id="item.id"
          @click="handleItemClick(item)"
        >
          <div class="relative overflow-hidden">
            <div
              v-if="!item.loaded"
              class="absolute inset-0 bg-gray-100 animate-pulse rounded-xl"
            />
            <img
              :src="item.cover"
              :alt="item.name"
              class="w-full h-auto object-contain transition-opacity duration-300 rounded-10"
              :class="{ 'opacity-0': !item.loaded }"
              @load="onImageLoad(item.id)"
            />
          </div>
          <div class="mt-8 text-999999 text-14">
            {{ item.name }}
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="py-4 flex justify-center">
      <div
        class="w-8 h-8 border-t-2 border-blue-500 border-solid rounded-full animate-spin"
      />
    </div>

    <!-- 没有更多数据提示 -->
    <div
      v-if="initialLoaded && finished && templateInfoList.records.length > 0"
      class="py-4 text-center text-gray-500 text-sm"
    >
      没有更多内容了
    </div>
    <!-- 暂无数据 -->
    <EmptyState
      v-if="initialLoaded && finished && templateInfoList.records.length === 0"
      class="mt-100"
    />
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  ref,
  onMounted,
  onUnmounted,
  watch,
  reactive,
  nextTick
} from "vue";
import type { TemplateInfoData } from "@/api/TemplateList";
import type { PropType } from "vue";
import { IMG_CDN_39 } from "@/constants";

const props = defineProps({
  // 模板信息列表
  templateInfoList: {
    type: Object as PropType<{
      current: number;
      pages: number;
      records: TemplateInfoData[];
      size: number;
      total: number;
    }>,
    required: true
  },
  // 是否正在加载
  loading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["load-more", "item-click"]);

// 处理点击事件
const handleItemClick = (item: TemplateInfoData) => {
  emit("item-click", item); // 提交点击的 item 数据给父组件
};

// 添加初始加载状态标记
const initialLoaded = ref(false);

// 使用响应式Map存储图片加载状态
const imageLoadedMap = reactive<Record<string, boolean>>({});

// 存储元素高度
const itemHeights = reactive<Record<string, number>>({});

// 处理加载状态的图片数据
const items = computed(() => {
  return props.templateInfoList.records.map(item => ({
    ...item,
    loaded: imageLoadedMap[item.id] || false
  }));
});

// 是否已加载完成
const finished = computed(() => {
  return props.templateInfoList.current >= props.templateInfoList.pages;
});

// 图片加载完成处理
const onImageLoad = (id: string) => {
  imageLoadedMap[id] = true;
  // 获取元素高度并存储
  const element = document.querySelector(`[data-id="${id}"]`);
  if (element) {
    itemHeights[id] = element.clientHeight;
  }
  // 图片加载完成后重新计算布局
  nextTick(calculateWaterfall);
};

// 瀑布流列数据
const leftColumnItems = ref<TemplateInfoData[]>([]);
const rightColumnItems = ref<TemplateInfoData[]>([]);

// 计算瀑布流布局
const calculateWaterfall = () => {
  const left: TemplateInfoData[] = [];
  const right: TemplateInfoData[] = [];

  // 计算左右列当前高度
  let leftHeight = 0;
  let rightHeight = 0;

  items.value.forEach(item => {
    const height = itemHeights[item.id] || 300; // 默认高度300px

    // 将项目添加到高度较小的列
    if (leftHeight <= rightHeight) {
      left.push(item);
      leftHeight += height;
    } else {
      right.push(item);
      rightHeight += height;
    }
  });

  leftColumnItems.value = left;
  rightColumnItems.value = right;
};

// 监听items变化重新计算瀑布流
watch(
  items,
  () => {
    // 在下一个tick执行以确保DOM已更新
    nextTick(() => {
      calculateWaterfall();
    });

    // 当有数据或加载完成时标记为已加载
    if (
      !initialLoaded.value &&
      (props.templateInfoList.records.length > 0 || finished.value)
    ) {
      initialLoaded.value = true;
    }
  },
  { deep: true }
);

// 滚动加载处理（添加防抖）
let scrollTimer: number | null = null;
const handleScroll = () => {
  if (props.loading || finished.value) return;

  // 防抖处理
  if (scrollTimer) clearTimeout(scrollTimer);
  scrollTimer = setTimeout(() => {
    const scrollThreshold = 100; // 距离底部100px时触发加载
    const scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    if (documentHeight - (scrollTop + windowHeight) < scrollThreshold) {
      emit("load-more");
    }
  }, 50) as unknown as number;
};

// 添加滚动监听
onMounted(() => {
  window.addEventListener("scroll", handleScroll);
  // 初始计算瀑布流
  nextTick(calculateWaterfall);
});

// 移除滚动监听
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
  if (scrollTimer) clearTimeout(scrollTimer);
});
</script>

<style scoped>
.waterfall-wrapper {
  display: flex;
  gap: 13px;
  justify-content: center;
}

.waterfall-column {
  flex: 1;
  max-width: calc(50% - 6.5px);
  display: flex;
  flex-direction: column;
  gap: 13px;
}

.waterfall-item {
  transition: transform 0.3s ease;
  break-inside: avoid;
}

.waterfall-item:hover {
  transform: translateY(-5px);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.waterfall-item {
  animation: fadeIn 0.5s ease forwards;
}
</style>
